/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *

  * Copyright (c) 2024 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "i2c.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdio.h"
#include "string.h"
#include "math.h"
#include "oled.h"
#include "sr04.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
#define Uart_Str_Strength 10
uint8_t RxData;                   // 用于存储接收到的数据//
uint8_t str[20];                  // OLED显示缓存数组
int leftSpeed;                    // 左轮速度
int rightSpeed;                   // 右轮速度
char Rxbuffer[Uart_Str_Strength]; // 用于存储长串的数�?
uint8_t receivedData = 0;         // 存储接收到的数据
uint8_t RxCount = 0;              // 用于接受数组计数
int F_x, F_y, F_z, F_u;
char uart_send_str[50];
int g_Distance1_cm;
int g_Distance2_cm;
int g_Distance3_cm;
int g_LeftSpeed, g_RightSpeed;
_Bool b_buletooth=1;
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
void Oled_Proc(void);
void Key_Proc(void);
void Motor_Proc(int left, int right);
void Follow_Proc(void);
void Uart_Proc(void);
void Min_Dis_Proc(void);
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
// 定义循迹引脚读取宏，从左到右，具体顺序自己试�?
#define LEFT1 HAL_GPIO_ReadPin(IN4_GPIO_Port, IN4_Pin) // 根据您的配置替换GPIOx和GPIO_PIN_x
#define LEFT2 HAL_GPIO_ReadPin(IN3_GPIO_Port, IN3_Pin) // 同上
#define LEFT3 HAL_GPIO_ReadPin(IN2_GPIO_Port, IN2_Pin) // 同上
#define LEFT4 HAL_GPIO_ReadPin(IN1_GPIO_Port, IN1_Pin) // 同上
/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
// 状�?�机的状�?   ----------------- 利用枚举的方式接�?----------------

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/**
 * @brief  The application entry point.
 * @retval int
 */
int main(void)
{

  /* USER CODE BEGIN 1 */

  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_I2C1_Init();
  MX_TIM2_Init();
  MX_TIM8_Init();
  MX_USART2_UART_Init();
  MX_TIM3_Init();
  /* USER CODE BEGIN 2 */
  /*自定义初始化*/
  HAL_GPIO_WritePin(BEEP_GPIO_Port, BEEP_Pin, GPIO_PIN_RESET); // 关闭蜂鸣�?

  /*初始化OLED*/
  OLED_Init();
  OLED_CLS();
  OLED_ON();
  //
  /*初始化电机驱�?*/
  HAL_GPIO_WritePin(AIN1_GPIO_Port, AIN1_Pin, GPIO_PIN_SET);
  HAL_GPIO_WritePin(AIN2_GPIO_Port, AIN2_Pin, GPIO_PIN_RESET);
  HAL_GPIO_WritePin(BIN1_GPIO_Port, BIN1_Pin, GPIO_PIN_SET);
  HAL_GPIO_WritePin(BIN2_GPIO_Port, BIN2_Pin, GPIO_PIN_RESET);
  HAL_TIM_PWM_Start(&htim8, TIM_CHANNEL_1);
  HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_4);
  __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_4, 0); // 设置初�?�度�?0
  __HAL_TIM_SET_COMPARE(&htim8, TIM_CHANNEL_1, 0);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */

  /*串口初始化，k210发�?�消息就可以进入中断*/
  HAL_UART_Receive_IT(&huart2, (uint8_t *)&RxData, 1); // 确保huart2与您的USART实例匹配
  while (1)
  {
    Oled_Proc();
		
		if(b_buletooth==0)
		{
    Min_Dis_Proc();
		}
		Motor_Proc(g_LeftSpeed, g_RightSpeed);
    HAL_Delay(200);
		
		
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
 * @brief System Clock Configuration
 * @retval None
 */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
   * in the RCC_OscInitTypeDef structure.
   */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
   */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */
void Min_Dis_Proc(void)
{
  if (g_Distance1_cm <= g_Distance2_cm && g_Distance1_cm <= g_Distance3_cm)
  {
    g_LeftSpeed = -130;
    g_RightSpeed = 130;
  }
  else if (g_Distance2_cm <= g_Distance1_cm && g_Distance2_cm <= g_Distance3_cm)
  {
    g_LeftSpeed = 200;
    g_RightSpeed = 200;
  }
  else if (g_Distance3_cm <= g_Distance1_cm && g_Distance3_cm <= g_Distance1_cm)
  {
    g_LeftSpeed = 130;
    g_RightSpeed = -130;
  }
}

void Uart_Proc(void)
{
}

void Oled_Proc(void)
{
  g_Distance1_cm = SR04_GetData(GPIOB, GPIO_PIN_2, GPIOB, GPIO_PIN_1);
  g_Distance2_cm = SR04_GetData(GPIOB, GPIO_PIN_0, GPIOC, GPIO_PIN_5);
  g_Distance3_cm = SR04_GetData(GPIOC, GPIO_PIN_4, GPIOA, GPIO_PIN_7);
  sprintf((char *)str, "Rig: %03dcm", g_Distance1_cm);
  OLED_ShowStr(0, 0, str, 2);
  sprintf((char *)str, "Mid: %03dcm", g_Distance2_cm);
  OLED_ShowStr(0, 2, str, 2);
  sprintf((char *)str, "Lef: %03dcm", g_Distance3_cm);
  OLED_ShowStr(0, 4, str, 2);
	sprintf((char *)str, "Rx: %03d", b_buletooth);
  OLED_ShowStr(0, 6, str, 2);
}

void Key_Proc(void)
{
  if (HAL_GPIO_ReadPin(UP_GPIO_Port, UP_Pin) == GPIO_PIN_RESET) // 上按键增加房间号
  {
    HAL_Delay(50);
    if (HAL_GPIO_ReadPin(UP_GPIO_Port, UP_Pin) == GPIO_PIN_RESET)
    {
    }
  }
  if (HAL_GPIO_ReadPin(DOWN_GPIO_Port, DOWN_Pin) == GPIO_PIN_RESET)
  {
    HAL_Delay(50);
    if (HAL_GPIO_ReadPin(DOWN_GPIO_Port, DOWN_Pin) == GPIO_PIN_RESET) // 下按键减少房间号
    {
    }
  }
  if (HAL_GPIO_ReadPin(LEFT_GPIO_Port, LEFT_Pin) == GPIO_PIN_RESET)
  {
    HAL_Delay(10);
    if (HAL_GPIO_ReadPin(LEFT_GPIO_Port, LEFT_Pin) == GPIO_PIN_RESET)
    {
    }
  }
  if (HAL_GPIO_ReadPin(RIGHT_GPIO_Port, RIGHT_Pin) == GPIO_PIN_RESET)
  {
    HAL_Delay(10);
    if (HAL_GPIO_ReadPin(RIGHT_GPIO_Port, RIGHT_Pin) == GPIO_PIN_RESET)
    {
    }
  }
  if (HAL_GPIO_ReadPin(OK_GPIO_Port, OK_Pin) == GPIO_PIN_RESET)
  {
    HAL_Delay(10);
    if (HAL_GPIO_ReadPin(OK_GPIO_Port, OK_Pin) == GPIO_PIN_RESET)
    {
    }
  }
}
void Motor_Proc(int left, int right)
{
  if (left >= 0)
  {
    HAL_GPIO_WritePin(AIN1_GPIO_Port, AIN1_Pin, GPIO_PIN_SET);
    HAL_GPIO_WritePin(AIN2_GPIO_Port, AIN2_Pin, GPIO_PIN_RESET);
  }
  else
  {
    HAL_GPIO_WritePin(AIN1_GPIO_Port, AIN1_Pin, GPIO_PIN_RESET);
    HAL_GPIO_WritePin(AIN2_GPIO_Port, AIN2_Pin, GPIO_PIN_SET);
  }
  if (right >= 0)
  {
    HAL_GPIO_WritePin(BIN1_GPIO_Port, BIN1_Pin, GPIO_PIN_SET);
    HAL_GPIO_WritePin(BIN2_GPIO_Port, BIN2_Pin, GPIO_PIN_RESET);
  }
  else
  {
    HAL_GPIO_WritePin(BIN1_GPIO_Port, BIN1_Pin, GPIO_PIN_RESET);
    HAL_GPIO_WritePin(BIN2_GPIO_Port, BIN2_Pin, GPIO_PIN_SET);
  }
  __HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_4, abs(right));
  __HAL_TIM_SET_COMPARE(&htim8, TIM_CHANNEL_1, abs(left));
}

void Follow_Proc(void)
{
  int left1 = LEFT1;
  int left2 = LEFT2;
  int left3 = LEFT3;
  int left4 = LEFT4;

  if (LEFT1 == 0 && LEFT2 == 1 && LEFT3 == 1 && LEFT4 == 0)
  {
    // 直行
    leftSpeed = 200;  // 400
    rightSpeed = 200; // 400
  }
  else if (LEFT1 == 0 && LEFT2 == 1 && LEFT3 == 0 && LEFT4 == 0)
  {
    // 轻微左转
    leftSpeed = 100;  // 200
    rightSpeed = 200; // 400
  }
  else if (LEFT1 == 0 && LEFT2 == 0 && LEFT3 == 1 && LEFT4 == 0)
  {
    // 轻微右转
    leftSpeed = 200;  // 400
    rightSpeed = 100; // 200
  }
  else if (LEFT1 == 1 && LEFT2 == 0 && LEFT3 == 0 && LEFT4 == 0)
  {
    // 大幅左转
    leftSpeed = 250; // 500
    rightSpeed = 50; // 100
  }
  else if (LEFT1 == 0 && LEFT2 == 0 && LEFT3 == 0 && LEFT4 == 1)
  {
    // 大幅右转
    leftSpeed = 50;   // 100
    rightSpeed = 250; // 500
  }
}

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
  if (huart->Instance == USART2)
  {
    // 处理串口1接收完成中断
    // 检查接收到的数据是否在1-9之间
    if (RxData >= '1' && RxData <= '9')
    {
      // 处理接收到的数据，这里你可以根据具体需求执行相关操作
      // 例如将接收到的数字转化为整数并打印
      uint8_t receivedNumber = RxData - '0'; // 转换为整数
                                                   // 你可以在这里添加自己的逻辑处理

      switch (receivedNumber)
      {
      case 1:
        g_LeftSpeed = 200;
        g_RightSpeed = 200;
        break;
      case 2:
        g_LeftSpeed = 160;
        g_RightSpeed = -160;
        break;
      case 3:
        g_LeftSpeed = -160;
        g_RightSpeed = 160;
        break;
      case 4:
        g_LeftSpeed = -200;
        g_RightSpeed = -200;
        break;
      case 5:
				b_buletooth^=1;
			  g_LeftSpeed = 0;
        g_RightSpeed = 0;

        break;
      case 6:
        break;
      case 7:
        break;
      case 8:
        break;
      case 9:
        g_LeftSpeed = 0;
        g_RightSpeed = 0;
        break;
      }
    }
		HAL_UART_Receive_IT(&huart2, (uint8_t *)&RxData, 1); // 确保huart1与您的USART实例匹配
  }
  else if (huart->Instance == USART1)
  {
    // 处理串口2接收完成中断
    Rxbuffer[RxCount++] = RxData;
    if (Rxbuffer[Uart_Str_Strength - 1] == 'a')
    {
      sscanf((char *)Rxbuffer, "%2d,%1d,%2d,%1da", &F_x, &F_y, &F_z, &F_u); // 接受到字符串3 6#，把3�?6分别保存两个int变量，但�?要串口发送的时�?�为整形int
      RxCount = 0;
      memset(Rxbuffer, 0, strlen(Rxbuffer));
    }
    if (RxCount == Uart_Str_Strength || RxData == 'a')
    {
      RxCount = 0;
      memset(Rxbuffer, 0, strlen(Rxbuffer));
    }

    
  }
}

/* USER CODE END 4 */

/**
 * @brief  This function is executed in case of error occurrence.
 * @retval None
 */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef USE_FULL_ASSERT
/**
 * @brief  Reports the name of the source file and the source line number
 *         where the assert_param error has occurred.
 * @param  file: pointer to the source file name
 * @param  line: assert_param error line source number
 * @retval None
 */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
